<?php
namespace App\Models\Traits;

use Cache;
use Image;
use Mexitek\PHPColors\Color;
trait ColorBaseHelper
{
    protected $baseColor = [
        'DE2020',
        'FE6C00',
        'FEBF00',
        '59A725',
        '892BCF',
        'D744BA',
        '06B7C8',
        '0065FE',
        '733413',
        'ffffff',
        '000000'
    ];

    /*
     *  计算颜色相似度
     */
    public function degree()
    {
        if ($this->basecolor) return $this->basecolor;
        $d = [];
        foreach ($this->baseColor as $basecolor) {
            $color1 = $this->rgb2hsl('#' . $basecolor);
            $color2 = $this->rgb2hsl(str_replace('0x', '#', $this->color));
            $d[$basecolor] = $this->distance($color1, $color2);
        }
        // 取最小值
        $min = collect($d)->min();
        $c = array_search($min, $d);
        $this->basecolor = $c;
        $this->save();
        return $c;
    }
    protected function rgb2hsl($color)
    {
      $_color = new Color($color);
      $hsl = $_color->getHsl();
      return $hsl;
    }
    public function distance($color1, $color2)
    {
        $R = 100;
        $angle = 30;
        $h = $R * cos($angle / 180 * M_PI);
        $r = $R * sin($angle / 180 * M_PI);
        $x1 = $r * $color1['L'] * $color1['S'] * cos($color1['H'] / 180 * M_PI);
        $y1 = $r * $color1['L'] * $color1['S'] * sin($color1['H'] / 180 * M_PI);
        $z1 = $h * (1 - $color1['L']);

        $x2 = $r * $color2['L'] * $color2['S'] * cos($color2['H'] / 180 * M_PI);
        $y2 = $r * $color2['L'] * $color2['S'] * sin($color2['H'] / 180 * M_PI);
        $z2 = $h * (1 - $color2['L']);
        $dx = $x1 - $x2;
        $dy = $y1 - $y2;
        $dz = $z1 - $z2;
        return sqrt($dx * $dx + $dy * $dy + $dz * $dz);
    }
}
